#!/bin/sh

OUTPUT_PATH=$1
SOURCE_PATH=$2
CONFIG_FILE="$OUTPUT_PATH/.config"
SCRIPTS_DIR="$SOURCE_PATH/scripts"
APPLETS_DIR="$OUTPUT_PATH/applets"

echo "当前运行路径: $(pwd)"

make -C $SOURCE_PATH ph_defconfig O=$OUTPUT_PATH
if [ ! -f "$OUTPUT_PATH/.config" ]; then
    echo "error:config工具编译失败或未生成"
    exit 1
fi

# 1. 编译applet_tables生成工具
echo "[1/8] 编译applet_tables工具"
cc -I"$OUTPUT_PATH/include" -o "$APPLETS_DIR/applet_tables" "$SOURCE_PATH/applets/applet_tables.c"
if [ ! -f "$APPLETS_DIR/applet_tables" ]; then
    echo "error:applet_tables工具编译失败或未生成"
    exit 1
fi

# 2. 生成bbconfigopts.h和bbconfigopts_bz2.h
echo "[2/8] 生成配置头文件"
"$SCRIPTS_DIR/mkconfigs" "$OUTPUT_PATH/include/bbconfigopts.h" "$OUTPUT_PATH/include/bbconfigopts_bz2.h"
if [ ! -f "$OUTPUT_PATH/include/bbconfigopts.h" ]; then
    echo "error:bbconfigopts.h文件未生成"
    exit 1
fi
if [ ! -f "$OUTPUT_PATH/include/bbconfigopts_bz2.h" ]; then
    echo "error:bbconfigopts_bz2.h文件未生成"
    exit 1
fi

# 3. 根据autoconf.h拆分成子头文件
echo "[3/8] 拆分头文件"
"$OUTPUT_PATH/scripts/basic/split-include" "$OUTPUT_PATH/include/autoconf.h" "$OUTPUT_PATH/include/config"
if [ ! -f "$OUTPUT_PATH/include/autoconf.h" ]; then
    echo "error:autoconf.h文件未生成"
    exit 1
fi

cd $OUTPUT_PATH
# 4. 生成common_bufsiz.h
echo "[4/8] 生成缓冲区大小定义"
"$SCRIPTS_DIR/generate_BUFSIZ.sh" "$OUTPUT_PATH/include/common_bufsiz.h"
if [ ! -f "$OUTPUT_PATH/include/common_bufsiz.h" ]; then
    echo "error:common_bufsiz.h文件未生成"
    exit 1
fi


export srctree=$SOURCE_PATH
export HOSTCC=gcc
# 5. 生成embedded_scripts.h
echo "[5/8] 生成嵌入式脚本定义"
"$SCRIPTS_DIR/embedded_scripts" "$OUTPUT_PATH/include/embedded_scripts.h" "$SOURCE_PATH/embed" "$SOURCE_PATH/applets_sh"
if [ ! -f "$OUTPUT_PATH/include/embedded_scripts.h" ]; then
    echo "error:embedded_scripts.h文件未生成"
    exit 1
fi

# 6. 生成applet_tables.h和NUM_APPLETS.h
echo "[6/8] 生成applet表格文件"
"$APPLETS_DIR/applet_tables" "$OUTPUT_PATH/include/applet_tables.h" "$OUTPUT_PATH/include/NUM_APPLETS.h"
if [ ! -f "$OUTPUT_PATH/include/applet_tables.h" ]; then
    echo "error:applet_tables.h文件未生成"
    exit 1
fi
if [ ! -f "$OUTPUT_PATH/include/NUM_APPLETS.h" ]; then
    echo "error:NUM_APPLETS.h文件未生成"
    exit 1
fi

echo "[7/8] 编译usage工具"
cc -I"$OUTPUT_PATH/include" -o "$APPLETS_DIR/usage" "$SOURCE_PATH/applets/usage.c"
if [ ! -f "$APPLETS_DIR/usage" ]; then
    echo "error:usage文件未生成"
    exit 1
fi

# 8. 生成usage_compressed.h和applets
echo "[8/8] 生成usage_compressed.h文件"
"$SOURCE_PATH/applets/usage_compressed" "$OUTPUT_PATH/include/usage_compressed.h" "$OUTPUT_PATH/applets"
if [ ! -f "$OUTPUT_PATH/include/usage_compressed.h" ]; then
    echo "error:usage_compressed.h文件未生成"
    exit 1
fi